<?php
/* @var $this SiteController */
$baseUrl = Yii::app()->baseUrl;
$this->pageTitle=Yii::app()->name;

$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl.'/js/markerclusterer_packed.js');
$cs->registerScriptFile($baseUrl.'/js/markerclusterer.js');
?>
<script type="text/javascript"
  src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBeHLm8rr0OwuP8zGCbo2q6LlY5b0IdQk4">
</script>

<script type="text/javascript">
	// map object
	var geocoder;
	var map;
	var infowindow;
	var markers = new Array();
	var markerCluster;
	var kmlLayer
	
	var service;
	
	function initialize() {
	    map = new google.maps.Map(document.getElementById('map-canvas'), {
	        zoom: 15,
	        center: new google.maps.LatLng(-34.9290, 138.6010),
	        mapTypeId: google.maps.MapTypeId.ROADMAP
	    });
	    
	    infowindow = new google.maps.InfoWindow();
		markerCluster = new MarkerClusterer(map, markers);
		
		map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('legend'));
		
		$.getJSON('http://cdn.newsapi.com.au:80/newscontent/?api_key=y8ta428vmcjath8zhfbswxq3&type=news_story&html=full%2Call',function(data) {news_handler(data)});
		
	 }
 	
	function send()
	 {
	  //clear marker on map
	  clear_markers();
	  
	  //constrcut a query
	  service =  $('input[name="services"]:checked').val();
	  postcode = $('input[name="postcode"]').val();
//	  var data=$("#search-form").serialize();
	  var data = 'SearchForm%5Bpostcode%5D='+postcode + '&SearchForm%5Bservice%5D='+ service;
		
	  //kml layer
	  kmlplayer();
	  
	  //send ajax request with the query
	  $.ajax({
	   type: 'POST',
	    url: '<?php echo Yii::app()->createAbsoluteUrl("site/search"); ?>',
	   data:data,
	   success:	function success_return (data){
				data_handler(data);
		},
	   error: function(data) { // if error occured
	         console.log("Error occured");
	    },
	  dataType:'json'
	  });
	}
	
	function autocenter() {
      //  Create a new viewpoint bound
      var bounds = new google.maps.LatLngBounds();
      //  Go through each...
      $.each(markers, function (index, marker) {
      bounds.extend(marker.position);
      });
      //  Fit these bounds to the map
      map.fitBounds(bounds);
    }
    
    function clear_markers(){
    	markerCluster.clearMarkers();
    	for (var i = 0; i < markers.length; i++ ) {
		    markers[i].setMap(null);
		}
    }
    
    function data_handler(data){
    	if(service=="community"){
	    	for (var x = 0; x < data.length; x++) {
					if(data[x]["Street Address"]!=""){
						var add_postfix =  data[x]["Street Address"]+" "+ data[x]["Supplemental Address 1"]+" "+data[x]["Suburb"]+" "+data[x]["State"]+" "+data[x]["Post code"];
						var services = data[x]["Org Name"]
				        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+add_postfix+'&sensor=false', null, (function (this_services,this_infowindow,this_add_postfix,this_markers,this_markerCluster) {
				            return function(address){
				            if (address.status == google.maps.GeocoderStatus.OK){
					            var p = address.results[0]["geometry"].location
					            var latlng = new google.maps.LatLng(p.lat, p.lng);
					            map.setCenter(p);
					            var marker = new google.maps.Marker({
					                position: latlng,
					                map: map,
					                title:this_add_postfix,
					                animation: google.maps.Animation.DROP
					            });
					            this_markers.push(marker);
					            var contentString = '<div id="content">'+
												      '<h4>'+address.results[0]["formatted_address"]+'</h4>'+
												      '<p>'+this_services+'</p>'+
												      '</div>';
									
							    google.maps.event.addListener(marker, 'click', function() {
							    this_infowindow.close();
								this_infowindow.setContent(contentString);
							      this_infowindow.open(map,marker);
							    });
							    
							    this_markerCluster.addMarker(marker);
				            }
				            }
				        })(services,infowindow,add_postfix,markers,markerCluster));
				        autocenter();
				        
					}
	    	}
    	}
    	else if(service=="centrelink"){
    		for (var x = 0; x < data.length; x++) {
	            var latlng = new google.maps.LatLng(data[x][9], data[x][8]);
	            var marker = new google.maps.Marker({
	                position: latlng,
	                map: map,
	                animation: google.maps.Animation.DROP
	            });
	            markers.push(marker);
	            var contentString = '<div>Centrelink</div>';
									
			    google.maps.event.addListener(marker, 'click', function() {
				  infowindow.setContent(contentString);
			      infowindow.open(map,this);
			    });
			    markerCluster.addMarker(marker);
        		autocenter();
				        
	    	}
    	}

    }
    
    function kmlplayer(){
    	if(kmlLayer!=null){
    		kmlLayer.setMap(null);
    		document.getElementById('legend').innerHTML =  null;
    	}
    	if(service=="bikeroute"){
    		kmlUrl = 'http://opendata.adelaidecitycouncil.com/bike_routes/bike_routes.kmz';
    	}else if(service=="bbq"){
    		kmlUrl = 'http://opendata.adelaidecitycouncil.com/bbqs/bbq-point.kmz';
    	}
    	else if(service=="onstreetparking"){
    		kmlUrl = 'http://opendata.adelaidecitycouncil.com/parking_machines/parking machines-point.kmz';
    	}
    	else if(service=="bikerack"){
    		kmlUrl = 'http://opendata.adelaidecitycouncil.com/bike_racks/bikeracks-point.kmz';
    	}
    	else if (service=="fountains"){
    		kmlUrl = 'http://opendata.adelaidecitycouncil.com/drinking_fountains/drinkingfountain-point.kmz';
    	}
    	else{
    		return ;
    	}
		var kmlOptions = {
		  suppressInfoWindows: true,
		  preserveViewport: false,
		  map: map
		};
		  kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);	
		  google.maps.event.addListener(kmlLayer, 'click', function(event) {
		    var content = event.featureData.infoWindowHtml;
			document.getElementById('legend').innerHTML= content;
		  });
    }
    
    function news_handler(data){
//    	for(var i=0;i<data.length;i++){
	    	var title = data['results'][0]['subtitle'];
	    	var description =  data['results'][0]['description'];
	    	var link = data['results'][0]['link']
	    	document.getElementById('news').innerHTML = '<a href="'+link+'"=>'+title+'</a>';
//    	}
    }
    
	
	google.maps.event.addDomListener(window, 'load', initialize);

 
</script>
<div id="legend" style="background: white; padding: 10px;">
</div>

<div class="col-md-12" >
	<div class="col-md-2" style="padding:0px">
			<div class="col-md-12">
				<div class="input-group">                               
				                  <input type="text" class="form-control input-sm" placeholder="Search" name="postcode">
				                  <span class="input-group-btn">
				                    <button type="submit" class="btn input-sm" onclick='send()'><span class="fui-search"></span></button>
				                  </span>
				</div>
			</div>
			<div class="col-md-12">
					<ul class="siderbar">
						<li>
							<label class="radio">
							  <input type="radio" name="services" value="centrelink" data-toggle="radio">
							  Centrelink
							</label>
						</li>
						<li>
							<label class="radio">
							  <input type="radio" name="services" value="upark" data-toggle="radio">
							  U-Park in city
							</label>
						</li>
						<li>
							<label class="radio">
							  <input type="radio" name="services" value="community" data-toggle="radio">
							  Community
							</label>
						</li>
						<li>
							<label class="radio">
							  <input type="radio" name="services" value="bikeroute" data-toggle="radio">
							  Bike Route in city
							</label>
						</li>
						<li>
							<label class="radio">
							  <input type="radio" name="services" value="bbq" data-toggle="radio">
							  BBQ in city 
							</label>
						</li>
						<li>
							<label class="radio">
							  <input type="radio" name="services" value="onstreetparking" data-toggle="radio">
							  Onstreet parking machine in city 
							</label>
						</li>
						<li>
							<label class="radio">
							  <input type="radio" name="services" value="bikerack" data-toggle="radio">
							  Bike Racks 
							</label>
						</li>
						<li>
							<label class="radio">
							  <input type="radio" name="services" value="playground" data-toggle="radio">
							  Playground 
							</label>
						</li>
						<li>
							<label class="radio">
							  <input type="radio" name="services" value="wifi" data-toggle="radio">
							  Free Wi-Fi 
							</label>
						</li>
						
						<li>
							<label class="radio">
							  <input type="radio" name="services" value="fountains" data-toggle="radio">
							  Drinking Fountains
							</label>
						</li>
					<ul/>
			</div>
	</div>
	<div class="col-md-8">
		<div id="map-canvas" style="width:100%;height:600px"/>
	</div>
	</div>
	<div class="col-md-2">
	<div id="news">
		
	</div>
			<ul class="siderbar">
				<li><button class="btn btn-hg btn-primary">XXXX</button></li>
				<li><button class="btn btn-hg btn-primary">XXXX</button></li>
				<li><button class="btn btn-hg btn-primary">XXXX</button></li>
				<li><button class="btn btn-hg btn-primary">XXXX</button></li>
			<ul/>
	</div>
</div>
<div class="col-md-12" style="height:400px" id="metro-container">
	<div class="col-md-12" style="height:200px" id="metro">
		<div class="col-md-5" style="height:100%; "></div> 
		<div class="col-md-3" style="height:100%; "></div> 
		<div class="col-md-4" style="height:100%; "></div>
	</div>
	<div class="col-md-12" style="height:200px" id="metro">
		<div class="col-md-5" style="height:100%; "></div> 
		<div class="col-md-4" style="height:100%; "></div> 
		<div class="col-md-3" style="height:100%; "></div>
	</div>
	<div class="col-md-12" style="height:200px" id="metro">
		<div class="col-md-3" style="height:100%; "></div> 
		<div class="col-md-5" style="height:100%; "></div> 
		<div class="col-md-4" style="height:100%; "></div>
	</div>
</div>
<?php
//$shp  = new SHPHelper();  
//$shpdata = $shp->readSHP(Yii::getPathOfAlias('webroot').'/database/centrelink/Centrelink.shp');
//print_r($shpdata[0]);
//$dbf = new DBFHelper();
//			$key_array =  array('Name','Longitude','Latitude');
//			$result = $dbf->readDBF(Yii::getPathOfAlias('webroot').'/database/centrelink/Centrelink.dbf',$key_array);
//			print_r($result[0]);
?>

